package cn.tedu.knows.portal.service.impl;

import cn.tedu.knows.portal.exception.ServiceException;
import cn.tedu.knows.portal.mapper.ClassroomMapper;
import cn.tedu.knows.portal.mapper.QuestionMapper;
import cn.tedu.knows.portal.mapper.UserRoleMapper;
import cn.tedu.knows.portal.model.Classroom;
import cn.tedu.knows.portal.model.User;
import cn.tedu.knows.portal.mapper.UserMapper;
import cn.tedu.knows.portal.model.UserRole;
import cn.tedu.knows.portal.service.IUserService;
import cn.tedu.knows.portal.vo.RegisterVo;
import cn.tedu.knows.portal.vo.UserVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2021-10-27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    //注入注册需要的各种依赖
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ClassroomMapper classroomMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public void registerStudent(RegisterVo registerVo) {
        //1.根据用户输入的邀请码获得班级信息
        QueryWrapper<Classroom> query = new QueryWrapper<>();
        query.eq("invite_code",registerVo.getInviteCode());
        Classroom classroom = classroomMapper.selectOne(query);

        //2.判断班级信息是否存在,不存在直接抛异常
        if (classroom==null){
            throw new ServiceException("邀请码错误!");
        }

        //3.根据用户输入的手机号,获得用户信息
        User user = userMapper.findUserByUsername(registerVo.getPhone());

        //4.如果能够获得用户信息,表示当前手机号啊已经被注册
        if (user!=null){
            throw new ServiceException("手机号已经被注册");
        }

        //5.对用户输入的密码进行加密
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        String pwd = "{bcrypt}"+encoder.encode(registerVo.getPassword());

        //6.实例化用户对象,为各个属性赋值,收集用户信息
        User u = new User()
                .setUsername(registerVo.getPhone())
                .setNickname(registerVo.getNickname())
                .setPassword(pwd)
                .setClassroomId(classroom.getId())
                .setCreatetime(LocalDateTime.now())
                .setEnabled(1)
                .setLocked(0)
                .setType(0);

        //7.执行新增用户对象的操作
        int num = userMapper.insert(u);
        if (num!=1){
            throw new ServiceException("数据库忙!");
        }

        //8.执行新增用户角色关系的操作
        UserRole userRole = new UserRole()
                .setUserId(u.getId())
                .setRoleId(2);
        num = userRoleMapper.insert(userRole);
        if (num!=1){
            throw new ServiceException("数据库忙!");
        }

    }



    private List<User> users  = new CopyOnWriteArrayList<>();

    private Map<String, User> teacherMap = new ConcurrentHashMap<>();


    @Override
    public List<User> getTeachers() {
        //判断tags是不是空
        if (users.isEmpty()) {

            synchronized (users) {
                if (users.isEmpty()) {
                    //查询所有标签
                    List<User> users = userMapper.findTeachers();
                    //将查询到的所有标签保存到缓存中
                    this.users.addAll(users);
                    //将所有标签也保存在Map缓存中
                    for (User u:users) {
                        teacherMap.put(u.getNickname(),u);
                    }
                }
            }
        }
        return users;
    }

    @Override
    public Map<String, User> getTeacherMap() {
        //如果当前Map是空
        if (teacherMap.isEmpty()){
            //让上面的方法将map赋值
            getTeachers();
        }
        return teacherMap;
    }

    @Autowired
    private QuestionMapper questionMapper;
    @Override
    public UserVo getUserVo(String username) {
        //查用户信息
        User user = userMapper.findUserByUsername(username);
        //查用户提问数
        int count = questionMapper.countQuestionByUserId(user.getId());
        //收藏数
        int collect = questionMapper.countCollectByUserId(user.getId());


        UserVo userVo = new UserVo()
                .setId(user.getId())
                .setUsername(user.getUsername())
                .setNickname(user.getNickname())
                .setQuestions(count)
                .setCollections(collect);

        return userVo;
    }

}
